import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:system_info2/system_info2.dart';

// 系统信息数据模型
class SystemInfoItem {
  final String key;
  final String value;

  SystemInfoItem(this.key, this.value);
}

void main() {
  // 在release模式下捕获所有错误
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.dumpErrorToConsole(details);
  };
  
  runZonedGuarded(() {
    debugPrint('Application started');
    runApp(const MyApp());
  }, (error, stackTrace) {
    // 捕获未处理的异步错误
    debugPrint('Error: $error');
    debugPrint('Stack trace: $stackTrace');
  });
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<SystemInfoItem> systemInfoList = [];
  bool isLoading = true;
  String? errorMessage;

  @override
  void initState() {
    super.initState();
    // 异步加载系统信息
    _loadSystemInfo();
  }

  Future<void> _loadSystemInfo() async {
    try {
      List<SystemInfoItem> newSystemInfoList = [];
      
      // 内核信息
      try {
        String kernelArchitecture = SysInfo.kernelArchitecture.toString();
        newSystemInfoList.add(SystemInfoItem('Kernel architecture', kernelArchitecture));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Kernel architecture', 'Error: $e'));
      }
      
      try {
        String rawKernelArchitecture = SysInfo.rawKernelArchitecture;
        newSystemInfoList.add(SystemInfoItem('Raw Kernel architecture', rawKernelArchitecture));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Raw Kernel architecture', 'Error: $e'));
      }
      
      try {
        String kernelBitness = SysInfo.kernelBitness.toString();
        newSystemInfoList.add(SystemInfoItem('Kernel bitness', kernelBitness));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Kernel bitness', 'Error: $e'));
      }
      
      try {
        String kernelName = SysInfo.kernelName;
        newSystemInfoList.add(SystemInfoItem('Kernel name', kernelName));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Kernel name', 'Error: $e'));
      }
      
      try {
        String kernelVersion = SysInfo.kernelVersion;
        newSystemInfoList.add(SystemInfoItem('Kernel version', kernelVersion));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Kernel version', 'Error: $e'));
      }
      
      // 操作系统信息
      try {
        String osName = SysInfo.operatingSystemName;
        newSystemInfoList.add(SystemInfoItem('Operating system name', osName));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Operating system name', 'Error: $e'));
      }
      
      try {
        String osVersion = SysInfo.operatingSystemVersion;
        newSystemInfoList.add(SystemInfoItem('Operating system version', osVersion));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Operating system version', 'Error: $e'));
      }
      
      // 用户信息
      try {
        String userDir = SysInfo.userDirectory;
        newSystemInfoList.add(SystemInfoItem('User directory', userDir));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('User directory', 'Error: $e'));
      }
      
      try {
        String userId = SysInfo.userId.toString();
        newSystemInfoList.add(SystemInfoItem('User id', userId));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('User id', 'Error: $e'));
      }
      
      try {
        String userName = SysInfo.userName;
        newSystemInfoList.add(SystemInfoItem('User name', userName));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('User name', 'Error: $e'));
      }
      
      try {
        String userSpaceBitness = SysInfo.userSpaceBitness.toString();
        newSystemInfoList.add(SystemInfoItem('User space bitness', userSpaceBitness));
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('User space bitness', 'Error: $e'));
      }

      // CPU核心信息
      try {
        final cores = SysInfo.cores;
        newSystemInfoList.add(SystemInfoItem('Number of core', cores.length.toString()));
        
        for (int i = 0; i < cores.length; i++) {
          final core = cores[i];
          newSystemInfoList.add(SystemInfoItem('Core $i - Architecture', core.architecture.toString()));
          newSystemInfoList.add(SystemInfoItem('Core $i - Name', core.name));
          newSystemInfoList.add(SystemInfoItem('Core $i - Socket', core.socket.toString()));
          newSystemInfoList.add(SystemInfoItem('Core $i - Vendor', core.vendor));
        }
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('CPU Core Info', 'Error: $e'));
      }
      
      // 内存信息
      try {
        const int megaByte = 1024 * 1024;
        String totalPhysicalMemory = '${SysInfo.getTotalPhysicalMemory() ~/ megaByte} MB';
        newSystemInfoList.add(SystemInfoItem('Total physical memory', totalPhysicalMemory));
        
        String freePhysicalMemory = '${SysInfo.getFreePhysicalMemory() ~/ megaByte} MB';
        newSystemInfoList.add(SystemInfoItem('Free physical memory', freePhysicalMemory));
        
        String totalVirtualMemory = '${SysInfo.getTotalVirtualMemory() ~/ megaByte} MB';
        newSystemInfoList.add(SystemInfoItem('Total virtual memory', totalVirtualMemory));
        
        String freeVirtualMemory = '${SysInfo.getFreeVirtualMemory() ~/ megaByte} MB';
        newSystemInfoList.add(SystemInfoItem('Free virtual memory', freeVirtualMemory));


        try {
          if (kReleaseMode) {
            debugPrint('Attempting to get virtualMemorySize in release mode with safer approach');
            try {
              String virtualMemorySize = '${SysInfo.getVirtualMemorySize() ~/ megaByte} MB';
              newSystemInfoList.add(SystemInfoItem('Virtual memory size', virtualMemorySize));
              debugPrint('Successfully got virtualMemorySize in release mode');
            } catch (e) {
              debugPrint('Failed to get virtualMemorySize in release mode: $e');
              newSystemInfoList.add(SystemInfoItem('Virtual memory size', 'Failed to get virtualMemorySize in release mode: $e'));
            }
          } else {
            // debug模式下保持原来的行为
            String virtualMemorySize = '${SysInfo.getVirtualMemorySize() ~/ megaByte} MB';
            newSystemInfoList.add(SystemInfoItem('Virtual memory size', virtualMemorySize));
            debugPrint('Successfully got virtualMemorySize in debug mode');
          }
        } catch (e) {
          debugPrint('Outer catch - Failed to get virtualMemorySize: $e');
          newSystemInfoList.add(SystemInfoItem('Virtual memory size', 'Error: $e'));
        }
      } catch (e) {
        newSystemInfoList.add(SystemInfoItem('Memory Info', 'Error: $e'));
      }

      setState(() {
        systemInfoList = newSystemInfoList;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        errorMessage = 'Failed to load system info: $e';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('系统信息'),
        ),
        body: isLoading
            ? const Center(child: CircularProgressIndicator())
            : errorMessage != null
                ? Center(
                    child: Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: Text(
                        errorMessage!, 
                        textAlign: TextAlign.center,
                        style: const TextStyle(color: Colors.red),
                      ),
                    ),
                  )
                : ListView.builder(
                    itemCount: systemInfoList.length,
                    itemBuilder: (context, index) {
                      final item = systemInfoList[index];
                      return Container(
                        padding: const EdgeInsets.all(12.0),
                        decoration: BoxDecoration(
                          border: Border(bottom: BorderSide(color: Colors.grey.shade200))
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '${item.key}:',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.blue.shade700
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text("  ${item.value}"),
                          ],
                        ),
                      );
                    },
                  ),
      ),
    );
  }
}
